﻿using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;

namespace BOL.Apps.GeneNetworkBrowser
{
    public static class Cryptography
    {
        /// <summary>
        /// Decrypts  a particular string with a specific Key
        /// </summary>
        public static string Decrypt(string stringToDecrypt, string sEncryptionKey)
        {
            try
            {
                var iv = new byte[]{ 10, 20, 30, 40, 50, 60, 70, 80 };
                var key = Encoding.UTF8.GetBytes(sEncryptionKey.Substring(0, 8));
                var des = new DESCryptoServiceProvider();
                var inputByteArray = Convert.FromBase64String(stringToDecrypt);
                var ms = new MemoryStream();
                var cs = new CryptoStream(ms, des.CreateDecryptor(key, iv), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                var encoding = Encoding.UTF8;

                return encoding.GetString(ms.ToArray());
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        /// <summary>
        /// Encrypts a particular string with a specific Key
        /// </summary>
        public static string Encrypt(string stringToEncrypt, string sEncryptionKey)
        {
            try
            {
                var iv = new byte[]{ 10, 20, 30, 40, 50, 60, 70, 80 };
                var key = Encoding.UTF8.GetBytes(sEncryptionKey.Substring(0, 8));
                var des = new DESCryptoServiceProvider();
                var inputByteArray = Encoding.UTF8.GetBytes(stringToEncrypt);
                var ms = new MemoryStream();
                var cs = new CryptoStream(ms, des.CreateEncryptor(key, iv), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();

                return Convert.ToBase64String(ms.ToArray());
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
    }
}
